from django.shortcuts import render

# Create your views here.
from rest_framework_jwt.views import JSONWebTokenAPIView
from .serializers import CustomJSONWebTokenSerializer
from rest_framework.views import APIView
from . import models
class LoginView(JSONWebTokenAPIView):

    serializer_class = CustomJSONWebTokenSerializer


import re
from rest_framework.response import Response
from rest_framework import status
from .utils import get_user_obj_by_account
class CheckPhoneView(APIView):
    def post(self,request):
        phone = request.data.get('phone')
        # 格式校验
        if not re.match('1\d{10}',phone):
            return Response({'error':'手机号格式有误！'},status=status.HTTP_400_BAD_REQUEST)

        # 校验手机号唯一性
        ret = get_user_obj_by_account(phone)
        if ret:
            return Response({'error': '手机号已经被注册！'}, status=status.HTTP_400_BAD_REQUEST)

        return Response({'msg': 'ok'})

import random
from rest_framework.generics import CreateAPIView
from .serializers import RegisterModelSerializer
from lyapi.libs.yuntongxun.send_sms import send_message
from lyapi.settings import contains


class RegisterView(CreateAPIView):
    queryset = models.User.objects.all()
    serializer_class = RegisterModelSerializer

from django_redis import get_redis_connection
class SMScodeView(APIView):

    def get(self,request):
        # / ?phone = 1213123
        phone = request.query_params.get('phone')
        # 手机号的各种校验
        # random.randint(0000,9999)
        # 生成验证码
        code = '%04d' % random.randint(0,9999)
        # 手机号格式
        user = get_user_obj_by_account(phone)
        if user:  # 手机号已经被注册过了
            return Response({'error':'手机号已经被注册！！！！！'},status=status.HTTP_400_BAD_REQUEST)
        # 保存验证码， 3分钟有效
        conn = get_redis_connection('sms_code')
        pipe = conn.pipeline()  #创建管道
        pipe.multi()  #开启批量操作  （事务，）
        # 在保存数据之前，先到redis中查询一下，是否在60秒内已经发送过短信了，如果能够获取到值，表示60秒内已经发送过了
        redis_inter_code = conn.get('sms_inter_%s' % phone)
        # redis_inter_code = pipe.get('sms_inter_%s' % phone)
        print('>>>>>', redis_inter_code)
        if redis_inter_code:
            return Response({'error': '60秒内已经发送过了哦'}, status=status.HTTP_400_BAD_REQUEST)
        # conn.set('name', 'chao')
        pipe.setex('sms_%s' % phone, contains.SMS_EXPIRE_TIME*60, code)
        pipe.setex('sms_inter_%s' % phone, contains.SMS_INTERVAL_TIME, code)

        pipe.execute()  # 批量执行了
        # print('开始发送短信啦！')
        # 发送验证码
        from mycelery.sms.tasks import send_sms
        send_sms.delay(code, phone)
        return Response({'msg': '短信发送成功，请查收'})
        # ret = send_message(code, phone)
        # if not ret:
        #     return Response({'error': '短信发送失败'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        # else:
        #     return Response({'msg': '短信发送成功，请查收'})